package 单例模式;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lenovo
 * Date: 2022-10-04
 * Time: 19:35
 */
class MyBlockQueue{
    int[] arr = new int[10];
    int head = 0;//头
    int tail = 0;//尾
    int size = 0;//计算器

    public void put(int n) throws InterruptedException {
        synchronized (this){
            //判满 阻塞
            while(size == arr.length){
                wait();//等待take里的notify来唤醒wait
            }
                arr[tail] = n;
                tail++;
                size++;
                //循环队列
                if(tail >=arr.length){
                    tail = 0;
                }
                notify();
            }

        }


    public Integer take() throws InterruptedException {
        synchronized (this){
            //判空 阻塞
            while(size == 0){
                synchronized (this){
                    wait();
                }
            }
            int ret = arr[head];
            head++;
            if(head >= arr.length){
                head =0;
            }
            size--;
            notify();
            return ret;
        }

    }

}
public class demo4 {
    public static void main(String[] args) throws InterruptedException {
        MyBlockQueue queue = new MyBlockQueue();
        Thread t1 = new Thread(()->{
            int n = 1;
            while(true){
                try {
                    queue.put(n);

                    System.out.println("生产者生产了:"+n);
                    n++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        });
        t1.start();
        Thread t2 = new Thread(()->{
           while (true){
               try {
                   int ret = queue.take();
                   System.out.println("消费者消费了:"+ret);
                   Thread.sleep(500);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });
        t2.start();

    }

}
